<?php
session_start();
require_once (__DIR__ . '/../inc/functions.php');
require_once (__DIR__ . '/Users.php');
require_once (__DIR__ . '/ContactMethods.php');

function IsLoggedIn()
{
	return UserId() != FALSE;
}

function UserId()
{
	if(!isset($_SESSION['User']))
		return FALSE;
	$user = $_SESSION['User'];
	if(!isset($user['id']))
		return FALSE;
	
	return $user['id'];
}

function User()
{
	if(!isset($_SESSION['User']))
		return FALSE;
	$user = $_SESSION['User'];
	return $user;	
}

function RequireLogin()
{
	global $rootUrl;
	if(!IsLoggedIn())
	{
		header("Location: $rootUrl/../W/Accounts/login?returnUrl=$_SERVER[REQUEST_URI]");
		die();
	}
}

function DoLogin($email, $password)
{
	
	// check for email empty 
	if (!empty($email))
	{
		// attempt to look up the email
		$contact=ContactMethods::Lookup('email',$email);
		// check for email is not associated with a real user
		if (array_key_exists('Server Error', $contact))
			$password = '';		
		else
			//look up the user
			$user=Users::Get($contact['userId']); 
		// check for password empty
		if(!empty($password))
		{
			// check for a match
			if ($password == $user['password'])
			{
				$_SESSION['cart']=null; // start fresh
				$_SESSION['User'] = array('firstName'=>$user['firstName'], 'lastName'=>$user['lastName'], 'id'=>$user['id'], 'email'=>$email);
				return true;
			}
		} // end if-password non-empty
	} // end if-email non-empty
	/**
	 * If we get here then one of the checks above failed and we dont have 
	 * a match. It doesn't matter why... 
	 */ 
	return array('Login Error' => 'Email and/or password incorrect');
}

function DoLogout()
{
	if(IsLoggedIn())
	{
		$_SESSION['User']=null;
		$_SESSION['cart']=null;
	}
}
